package com.cl.ks.service;

import com.cl.ks.entity.KsFlowLike;
import com.cl.ks.repository.KsFlowLikeRepository;
import com.cl.mvc.service.JDBaseService;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.apache.spark.sql.catalyst.expressions.Like;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static com.cl.ks.constant.QTableConstant.qKsFlowLike;

@Service
public class KsFlowLikeService extends JDBaseService<KsFlowLike> {
    private final KsFlowLikeRepository ksFlowLikeRepository;

    private final JPAQueryFactory queryFactory;

    protected KsFlowLikeService(KsFlowLikeRepository ksFlowLikeRepository, JPAQueryFactory queryFactory) {
        super(ksFlowLikeRepository);
        this.ksFlowLikeRepository = ksFlowLikeRepository;
        this.queryFactory = queryFactory;
    }

    public KsFlowLike toggleLike(String auth, Integer targetId, String targetType) {

        Integer userId = jwtUtil.getUserId(auth);

        KsFlowLike existingLike = queryFactory.selectFrom(qKsFlowLike).where(qKsFlowLike.targetType.eq(targetType).and(qKsFlowLike.createdBy.eq(String.valueOf(userId)).and(qKsFlowLike.targetId.eq(targetId)))).fetchFirst();

        if (existingLike != null) {
            // 如果已经点赞，取消点赞
            if (existingLike.getStatus() == 1) {
                existingLike.setStatus(0);
            } else {
                // 如果已经取消点赞，重新点赞
                existingLike.setStatus(1);
            }
            return save(existingLike,auth);
        } else {
            // 如果没有点赞记录，创建新的点赞记录
            KsFlowLike newLike = new KsFlowLike();
            newLike.setTargetId(targetId);
            newLike.setTargetType(targetType);
            newLike.setStatus(1);
            return save(newLike,auth);
        }
    }

}
